package com.sgl.blog.controller.user;

import com.sgl.blog.pojo.BlogAccount;
import com.sgl.blog.service.AccountService;
import com.sgl.blog.service.ArticleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class LoginController {


    @Resource
    private AccountService accountService;

    @Resource
    private ArticleService articleService;

    /**
     * @return 转发到登录页
     */
    @GetMapping("login")
    public String loginPage(){
        return "login";
    }


    /**
     * @return 转发到忘记密码页
     */
    @GetMapping("forgotPassword")
    public String forgotPasswordPage(){
        return "forgotPassword";
    }


    /**
     * 账号登录
     * @param account 接收登录的账号
     * @return 登录成功返回到主界面，失败返回登录界面
     */
    @PostMapping("login")
    public String login(BlogAccount account, HttpSession session, Model model) {
        // 调用方法 查询数据库是否有此账户
        BlogAccount blog = accountService.login(account);
        // 将用户信息存入session
        session.setAttribute("account", blog);
        model.addAttribute("msg",0);
        // 设置回话时间直到浏览器关闭
        // session.setMaxInactiveInterval(0);
        model.addAttribute("sgl_list", articleService.findBlogByPage(1));
        return blog == null ? "login" : "/blog/list";
    }


    @GetMapping("logout")
    public String logout(HttpSession session, Model model) {
        session.invalidate();
        model.addAttribute("msg",2);
        return "/blog/list";
    }
}
